package ro.imv.server.gcmDatastore;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;

@SuppressWarnings("serial")
public class SendGCM2Clients extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(SendGCM2Clients.class.getName());
	
    @Override
    @SuppressWarnings("deprecation")
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String senderId = "1020560749606";//req.getParameter("senderId");
        String apiKey = "AIzaSyBy3lOtTFWiUy-Cj2DYdORmcIkJwvmzyBU";//req.getParameter("apiKey");
        String title = req.getParameter("title");
        String message = req.getParameter("message");
        String url = req.getParameter("url");
        String regId = req.getParameter("registrationId");
        
        try{
	        if (senderId != null && !"".equalsIgnoreCase(senderId)) {
	        	List<String> devices = new ArrayList<String>();
	        	if(null != regId){
	        		devices.add(regId);
	        		MulticastResult result = sendMessageToDevice(apiKey, devices, title, message, url);
	
	                resp.getWriter().println("GCM Message fields:");
	                resp.getWriter().println("title: " + title);
	                resp.getWriter().println("message:" + message);
	                resp.getWriter().println("url: " + url);
	                resp.getWriter().println("Message sent to this number of devices:" + devices.size());
	                resp.getWriter().println("This API key was used: " + apiKey);
	                resp.getWriter().println("The result is: " + result);
	        	}
//	        	else{
//	                DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
//	                Query query = new Query("Client");
//	                query = query.addFilter("senderId", FilterOperator.EQUAL, senderId);
//	                PreparedQuery preparedQuery = datastore.prepare(query);
//	                List<Entity> entities = preparedQuery.asList(FetchOptions.Builder.withLimit(1000));
//	                resp.setContentType("text/plain");
//	                resp.setCharacterEncoding("UTF-8");
//	                if (entities.size() != 0) {
//	                    for (Entity entity : entities) {
//	                        devices.add((String)entity.getProperty("registrationId"));
//	                    }
//	                    MulticastResult result = sendMessageToDevice(apiKey, devices, title, message, url);
//	
//	                    resp.getWriter().println("GCM Message fields:");
//	                    resp.getWriter().println("title: " + title);
//	                    resp.getWriter().println("message:" + message);
//	                    resp.getWriter().println("url: " + url);
//	                    resp.getWriter().println("Message sent to this number of devices:" + devices.size());
//	                    resp.getWriter().println("This API key was used: " + apiKey);
//	                    resp.getWriter().println("The result is: " + result);
//	                } else {
//	                    resp.getWriter().println(
//	                            "Are you sure, you provided correct sender Id? There is no devices registered for this senderId:"
//	                                    + senderId);
//	                }
//	        	}
	        } else {
	            resp.getWriter()
	                    .println(
	                            "Please provide your senderId in the URL parameter. Something like this: http://gcm4public.appspot.com/registeredgcmclients?senderId=716163315987");
	        }
        }catch(Exception ex){
        	resp.getWriter()
            .println("An error has occured: " + ex.getMessage());
        }
    }

    private MulticastResult sendMessageToDevice(String apiKey, List<String> devices, String title, String message, String url) {
    	log.log(Level.INFO, "In sendMessageToDevice");
        Sender sender = new Sender(apiKey);
        Message gcmMessage = new Message.Builder().addData("title", title).addData("message", message).addData("url", url).build();
        MulticastResult result = null;
        try {
            result = sender.send(gcmMessage, devices, 5);
        } catch (IOException e) {
        	log.log(Level.SEVERE, "In sendMessageToDevice");
            e.printStackTrace();
        }
        return result;
    }
}